<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.7.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.4.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.4.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="今天来研究一下onTouch函数的返回值。 首先在一个ImageView中添加一个监听器：1234567mImageView.setOnTouchListener(new View.OnTouchListener() &amp;#123;    @Override    public boolean onTouch(View v, MotionEvent event) &amp;#123;        Log.">
<meta name="keywords" content="android">
<meta property="og:type" content="article">
<meta property="og:title" content="onTouchListener中的onTouch函数">
<meta property="og:url" content="https://ricky9090.github.io/2016/06/28/ontouchlistener_note/index.html">
<meta property="og:site_name" content="Ricky&#39;s Blog">
<meta property="og:description" content="今天来研究一下onTouch函数的返回值。 首先在一个ImageView中添加一个监听器：1234567mImageView.setOnTouchListener(new View.OnTouchListener() &amp;#123;    @Override    public boolean onTouch(View v, MotionEvent event) &amp;#123;        Log.">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-06-11T08:46:44.049Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="onTouchListener中的onTouch函数">
<meta name="twitter:description" content="今天来研究一下onTouch函数的返回值。 首先在一个ImageView中添加一个监听器：1234567mImageView.setOnTouchListener(new View.OnTouchListener() &amp;#123;    @Override    public boolean onTouch(View v, MotionEvent event) &amp;#123;        Log.">
  <link rel="canonical" href="https://ricky9090.github.io/2016/06/28/ontouchlistener_note/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>onTouchListener中的onTouch函数 | Ricky's Blog</title>
  








  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Ricky's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">A long way to go.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-about">
      
    

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="https://ricky9090.github.io/2016/06/28/ontouchlistener_note/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Ricky">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Ricky's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">onTouchListener中的onTouch函数

          
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2016-06-28 17:41:09" itemprop="dateCreated datePublished" datetime="2016-06-28T17:41:09+08:00">2016-06-28</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2018-06-11 16:46:44" itemprop="dateModified" datetime="2018-06-11T16:46:44+08:00">2018-06-11</time>
              </span>
            
          

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>今天来研究一下onTouch函数的返回值。</p>
<p>首先在一个ImageView中添加一个监听器：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">mImageView.setOnTouchListener(<span class="keyword">new</span> View.OnTouchListener() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onTouch</span><span class="params">(View v, MotionEvent event)</span> </span>&#123;</span><br><span class="line">        Log.i(TAG, <span class="string">"onTouch "</span> + event.getAction());</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></p>
<a id="more"></a>
<p>代码很简单，我们仅打印了一下event的<code>getAction()</code>值，然后默认返回了一个false。<br>在这里返回true或false有何意义呢？SDK文档是这样写的：</p>
<blockquote>
<p>True if the listener has consumed the event, false otherwise.</p>
</blockquote>
<p><strong>返回true说明监听函数消费了这次touch事件，返回false向上层说明监听没有消费这次事件。</strong></p>
<p>实际文档这样说还是不明白：怎么叫消费，是否消费会造成什么影响？<br>用实践来检验，分别返回true与false运行程序进行实验：</p>
<table>
<thead>
<tr>
<th>返回值</th>
<th>Log</th>
</tr>
</thead>
<tbody>
<tr>
<td>true</td>
<td>手指接触view-&gt;在view上移动-&gt;抬起，一直打印getAction日志</td>
</tr>
<tr>
<td>false</td>
<td>手指接触view打印ACTION_DOWN；在view上移动-&gt;抬起，无日志打印</td>
</tr>
</tbody>
</table>
<p><br><br>看起来返回值会对listener的调用产生影响，由于在onTouch中直接打印日志，那么表明<strong>返回false则会导致后续产生Touch事件根本不会调用onTouch函数</strong>。</p>
<p>这是为何？只能看源码来寻求答案了。<br>首先由注册onTouchListener方法得知，onTouch肯定是在View类中被调用的。首先查找到listener被注册到何处：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setOnTouchListener</span><span class="params">(OnTouchListener l)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// onTouchListener被赋值到View中getListenerInfo().mOnTouchListener</span></span><br><span class="line">    getListenerInfo().mOnTouchListener = l;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>接下来找到<code>mOnTouchListener.onTouch()</code> 这样的语句，在View的<code>dispatchTouchEvent</code> 中：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (li != <span class="keyword">null</span> &amp;&amp; li.mOnTouchListener != <span class="keyword">null</span> &amp;&amp; (mViewFlags &amp; ENABLED_MASK) == ENABLED</span><br><span class="line">        &amp;&amp; li.mOnTouchListener.onTouch(<span class="keyword">this</span>, event)) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在API 23上，<code>dispatchTouchEvent</code> 函数共计51行，而对比API 19，此函数代码仅22行。API 23上源码中诸如<code>stopNestedScroll</code> 函数是API 21才引入的，而onTouch事件的响应在新老版本上保持一致，因此研究API 19的代码就可以了，新特性的处理暂不涉及。</p>
<p>在API 19 中，dispatchTouchEvent的源码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">dispatchTouchEvent</span><span class="params">(MotionEvent event)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 根据源码注释，InputEventConsistencyVerifier仅用于Debug</span></span><br><span class="line">    <span class="keyword">if</span> (mInputEventConsistencyVerifier != <span class="keyword">null</span>) &#123;</span><br><span class="line">        mInputEventConsistencyVerifier.onTouchEvent(event, <span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (onFilterTouchEventForSecurity(event)) &#123;</span><br><span class="line">        <span class="comment">//noinspection SimplifiableIfStatement</span></span><br><span class="line">        ListenerInfo li = mListenerInfo;</span><br><span class="line">        <span class="keyword">if</span> (li != <span class="keyword">null</span> &amp;&amp; li.mOnTouchListener != <span class="keyword">null</span> &amp;&amp; (mViewFlags &amp; ENABLED_MASK) == ENABLED</span><br><span class="line">                &amp;&amp; li.mOnTouchListener.onTouch(<span class="keyword">this</span>, event)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (onTouchEvent(event)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (mInputEventConsistencyVerifier != <span class="keyword">null</span>) &#123;</span><br><span class="line">        mInputEventConsistencyVerifier.onUnhandledEvent(event, <span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>代码很短，可以很快浏览完。其中<code>InputEventConsistencyVerifier</code> 类在源码中注释：</p>
<blockquote>
<p>Checks whether a sequence of input events is self-consistent. Logs a description of each problem detected.<br>When a problem is detected, the event is tainted. This mechanism prevents the same error from being reported multiple times.</p>
</blockquote>
<p>可以看到这个类主要是检验输入事件的完整性的，对View类没有实质性影响。<br>另外一个onFilterTouchEventForSecurity通过源码注释可以判断在应用前台时均会返回true。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onFilterTouchEventForSecurity</span><span class="params">(MotionEvent event)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//noinspection RedundantIfStatement</span></span><br><span class="line">    <span class="keyword">if</span> ((mViewFlags &amp; FILTER_TOUCHES_WHEN_OBSCURED) != <span class="number">0</span></span><br><span class="line">            &amp;&amp; (event.getFlags() &amp; MotionEvent.FLAG_WINDOW_IS_OBSCURED) != <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="comment">// Window is obscured, drop this touch.</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>那么对观察现象产生影响的只可能是<strong>中间的两个if判断</strong>了。</p>
<p>在此结合dispatch函数整理一下点击ImageView时的逻辑，<br>从上至下先进入我们设置的onTouchListener判断中，再进入View的onTouchEvent函数中，因此：</p>
<table>
<thead>
<tr>
<th>onTouchListener返回值</th>
<th>onTouchEvent</th>
<th>dispatch返回值</th>
</tr>
</thead>
<tbody>
<tr>
<td>true</td>
<td>不会处理</td>
<td>true</td>
</tr>
<tr>
<td>false</td>
<td>未知</td>
<td>未知</td>
</tr>
</tbody>
</table>
<p><br><br>由我们目前得到的数据，在listener返回false时，后两项确实是未知的。因此还要验证一下View中的onTouchEvent到底会返回什么。</p>
<p>验证的方法不难：创建一个子类继承ImageView，仅覆写onTouchEvent函数，打印<code>super.onTouchEvent</code> 的返回值。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyImageView</span> <span class="keyword">extends</span> <span class="title">ImageView</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String TAG = <span class="string">"MyImageView"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MyImageView</span><span class="params">(Context context, AttributeSet attrs)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(context, attrs);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onTouchEvent</span><span class="params">(MotionEvent event)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">boolean</span> upperOnTouch = <span class="keyword">super</span>.onTouchEvent(event);</span><br><span class="line">        Log.i(TAG, <span class="string">"super ImageView onTouchEvent return: "</span> + upperOnTouch);</span><br><span class="line">        <span class="keyword">return</span> upperOnTouch;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在listener返回false时，运行代码打印log：</p>
<blockquote>
<p>06-28 17:26:59.235 3939-3939/com.example.gesturetest I/MyImageView: super ImageView onTouchEvent return: false</p>
</blockquote>
<p>也就是说目前为止，View中的onTouchEvent没有对我们listener的返回产生影响（通过查看ImageView可以发现其中并没有覆写View的onTouchEvent方法，因此可以去掉ImageView的影响了）。上面的表可以更新为：</p>
<table>
<thead>
<tr>
<th>onTouchListener返回值</th>
<th>onTouchEvent</th>
<th>dispatch返回值</th>
</tr>
</thead>
<tbody>
<tr>
<td>true</td>
<td>不会处理</td>
<td>true</td>
</tr>
<tr>
<td>false</td>
<td>false</td>
<td>false</td>
</tr>
</tbody>
</table>
<p><br><br><strong>目前为止的总体结论：</strong></p>
<table>
<thead>
<tr>
<th>onTouchListener返回值</th>
<th>Log</th>
<th>说明（所测试ImageView）</th>
</tr>
</thead>
<tbody>
<tr>
<td>true</td>
<td>手指接触view-&gt;在view上移动-&gt;抬起，一直打印getAction日志</td>
<td>处理了过程中所有的Touch事件</td>
</tr>
<tr>
<td>false</td>
<td>手指接触view打印ACTION_DOWN；在view上移动-&gt;抬起，无日志打印</td>
<td>仅处理了ACTION_DOWN事件，后面的所有事件都未处理</td>
</tr>
</tbody>
</table>
<p><br><br>可以推断，假设ImageView中onTouch返回true，上层的调用者拿到true后，后续再有事件，就会继续把事件传递给这个ImageView；若ImageView中onTouch返回了false，则上层后续不会再把Touch事件传递给ImageView了。<br>那么这个上层明显就是ImageView在XML中的上级节点了。假设ImageView布局写在LinearLayout中，那么传递给ImageView事件的上层就是LinearLayout。因此最终需要查看ViewGroup类的源码。<br>ViewGroup实际继承于View，因此也有dispatchTouchEvent函数，不过已经将其完全覆写。<br>在ViewGroup中查找子View<code>dispatchTouchEvent</code> 函数的调用，发现是在<code>dispatchTransformedTouchEvent</code> 函数中，ViewGroup需要将接收到的事件进行转换（例如坐标）；再进一步查找<code>dispatchTransformedTouchEvent</code> 的调用，发现就是在ViewGroup的<code>dispatchTouchEvent</code> 中。<br>整体流程大致为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">???-&gt;ViewGroup: dispatchTouchEvent()</span><br><span class="line">ViewGroup-&gt;ViewGroup: dispatchTransformedTouchEvent()</span><br><span class="line">ViewGroup-&gt;View(Child): dispatchTouchEvent()</span><br><span class="line">View(Child)-&gt;View(Child): onTouchListener.onTouch()</span><br><span class="line">View(Child)-&gt;View(Child): onTouchEvent()</span><br><span class="line">View(Child)--&gt;&gt;ViewGroup: return</span><br><span class="line">ViewGroup--&gt;&gt;???: return</span><br></pre></td></tr></table></figure></p>
<p>在这里推测是<code>dispatchTouchEvent</code> 函数中的逻辑进行了处理。<code>dispatchTransformedTouchEvent</code> 函数声明是：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">dispatchTransformedTouchEvent</span><span class="params">(MotionEvent event, <span class="keyword">boolean</span> cancel,</span></span></span><br><span class="line"><span class="function"><span class="params">            View child, <span class="keyword">int</span> desiredPointerIdBits)</span></span></span><br></pre></td></tr></table></figure></p>
<p><br><br>因此调用<code>dispatchTransformedTouchEvent</code> 是需要指定View的。如果是在这个函数中处理，当我们的ImageView不再接收任何Touch事件时，每次Touch事件都需要调用<code>dispatchTransformedTouchEvent</code>，效率就会降低。从这个角度，猜测真正是在<code>dispatchTouchEvent</code> 中进行了处理。<br>接下来整理ViewGroup中<code>dispatchTouchEvent</code> 的逻辑，首先会判断这个事件是否是一个ACTION_DOWN，如果是ACTION_DOWN，表明用户刚刚点击屏幕，是一系列Touch事件的起始，因此会调用<code>cancelAndClearTouchTargets</code> 与<code>resetTouchState</code> 复位状态。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Handle an initial down.</span></span><br><span class="line"><span class="keyword">if</span> (actionMasked == MotionEvent.ACTION_DOWN) &#123;</span><br><span class="line">    <span class="comment">// Throw away all previous state when starting a new touch gesture.</span></span><br><span class="line">    <span class="comment">// The framework may have dropped the up or cancel event for the previous gesture</span></span><br><span class="line">    <span class="comment">// due to an app switch, ANR, or some other state change.</span></span><br><span class="line">    cancelAndClearTouchTargets(ev);</span><br><span class="line">    resetTouchState();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><br><br>再接下来处理ViewGroup拦截Touch事件的逻辑：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Check for interception.</span></span><br><span class="line"><span class="keyword">final</span> <span class="keyword">boolean</span> intercepted;</span><br><span class="line"><span class="keyword">if</span> (actionMasked == MotionEvent.ACTION_DOWN</span><br><span class="line">        || mFirstTouchTarget != <span class="keyword">null</span>) &#123;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">boolean</span> disallowIntercept = (mGroupFlags &amp; FLAG_DISALLOW_INTERCEPT) != <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span> (!disallowIntercept) &#123;</span><br><span class="line">        intercepted = onInterceptTouchEvent(ev);</span><br><span class="line">        ev.setAction(action); <span class="comment">// restore action in case it was changed</span></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        intercepted = <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// There are no touch targets and this action is not an initial down</span></span><br><span class="line">    <span class="comment">// so this view group continues to intercept touches.</span></span><br><span class="line">    intercepted = <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><br><br>整个流程大致为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">st=&gt;start: if</span><br><span class="line">cond_action=&gt;condition: ACTION_DOWN ?</span><br><span class="line">cond_touchTarget=&gt;condition: FirstTouchTarget不为空</span><br><span class="line">op_interceptTouch=&gt;operation: intercepted = onInterceptTouchEvent()</span><br><span class="line">op_interceptTure=&gt;operation: intercepted = true</span><br><span class="line">op_interceptFalse=&gt;operation: intercepted = false</span><br><span class="line">cond_allowIntercept=&gt;condition: 允许Intercept ?</span><br><span class="line">e=&gt;end</span><br><span class="line"></span><br><span class="line">st-&gt;cond_action</span><br><span class="line">cond_action(yes)-&gt;cond_allowIntercept</span><br><span class="line">cond_action(no)-&gt;cond_touchTarget</span><br><span class="line">cond_allowIntercept(yes)-&gt;op_interceptTouch-&gt;e</span><br><span class="line">cond_allowIntercept(no)-&gt;op_interceptFalse-&gt;e</span><br><span class="line">cond_touchTarget(yes)-&gt;cond_allowIntercept</span><br><span class="line">cond_touchTarget(no)-&gt;op_interceptFalse</span><br></pre></td></tr></table></figure></p>

    </div>

    
    
    
        
      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/android/" rel="tag"># android</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/2016/06/02/drawerlayout_note/" rel="next" title="DrawerLayout的使用">
                  <i class="fa fa-chevron-left"></i> DrawerLayout的使用
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/2016/06/30/android_unit_test/" rel="prev" title="Android Studio中的单元测试">
                  Android Studio中的单元测试 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Ricky</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">54</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/ricky9090" title="GitHub &rarr; https://github.com/ricky9090" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ricky</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.7.1</div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.4.0</div>

        












        
      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js?v=3.1.0"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/pisces.js?v=7.4.0"></script>

<script src="/js/next-boot.js?v=7.4.0"></script>



  





















  

  

  

</body>
</html>
